import ENV from './env';
// import CONSTANTS from './constants'
import type { options } from '@/model/request/services'

const request = (options: options) => {
    let headers: any = {}
    let token = uni.getStorageSync('user_token')
    if (options.content_type != undefined) {
        headers = {
            'content-type': options.content_type,
        }
    }
    if (token) {
        headers.authorization = 'Bearer ' + token
    }
    return new Promise((resolved, rejected) => {

        uni.request({
            url: ENV.baseUrl + options.url,
            header: headers,
            method: options.method,
            data: options.data,
            success: (res: any) => {
                if (res.data.code != 200) {
                    let icon_type: "error" | "success" | "loading" | "none" | "fail" | "exception" | undefined = 'error'
                    if (res.data.code == 300) {
                        icon_type = 'none'
                    }
                    if (res.data.message.indexOf('请重新登录') > -1) {
                        if(token){
                            uni.removeStorage({
                                key: 'user_token'
                            });
                        }
                    }
                    uni.showToast({
                        icon: icon_type,
                        duration: 3000,
                        title: res.data.message || '服务器错误,请稍后再试'
                    });
                    resolved(res.data)
                    return
                }
                resolved(res.data)
            },
            fail: (err) => {
                uni.showToast({
                    icon: 'error',
                    duration: 3000,
                    title: '服务器错误,请稍后再试'
                });
                rejected(err);
            }
        })
    })

}

// const request

export { request }
